package com.tedu.ivos.audit.service.impl;

import com.tedu.ivos.application.mapper.ApplicationMapper;
import com.tedu.ivos.application.pojo.entity.Application;
import com.tedu.ivos.audit.mapper.AuditMapper;
import com.tedu.ivos.audit.pojo.dto.AuditQuery;
import com.tedu.ivos.audit.pojo.dto.AuditSaveParam;
import com.tedu.ivos.audit.pojo.entity.Audit;
import com.tedu.ivos.audit.pojo.vo.AuditVO;
import com.tedu.ivos.audit.service.AuditService;
import com.tedu.ivos.base.enums.ApplicationStatusEnum;
import com.tedu.ivos.base.enums.AuditStatusEnum;
import com.tedu.ivos.user.mapper.UserMapper;
import com.tedu.ivos.user.pojo.vo.UserVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

@Transactional
@Slf4j
@Service
public class AuditServiceImpl implements AuditService {

    @Autowired
    private AuditMapper auditMapper;
    @Autowired
    private ApplicationMapper applicationMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public void insertAudit(Application application) {
        log.debug("为传入的申请单创建对应的审批单业务，参数：{}",application);
        List<Long> userIdList = application.getAuditUserIdList();
        for (int i = 0; i < userIdList.size(); i++){
            Audit audit = new Audit();
            audit.setApplicationId(application.getId());
            audit.setAuditUserId(userIdList.get(i));
            audit.setAuditSort(i);
            if (i == 0){
                audit.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
            } else {
                audit.setAuditStatus(AuditStatusEnum.PENDING.getCode());
            }
            audit.setCreateTime(new Date());
            auditMapper.insert(audit);
        }
    }

    @Override
    public List<AuditVO> selectAuditByApplicationId(Long id) {
        log.debug("根据申请单id查询对应的审批单业务，参数：{}",id);
        List<AuditVO> list = auditMapper.selectAuditByApplicationId(id);

        return list;

    }

    @Override
    public List<AuditVO> selectAudit(AuditQuery auditQuery) {
        log.debug("查询审核记录业务,{}", auditQuery);
        List<AuditVO> list = auditMapper.selectAudit(auditQuery);
        // 获取审核人姓名
        for (int i = 0; i < list.size(); i++) {
            AuditVO auditVO = list.get(i);
            assignAuditUserList(auditVO);
        }

        return list;
    }

    @Override
    public void updateAudit(AuditSaveParam auditSaveParam) {
        log.debug("审批单业务:{}", auditSaveParam);
        Audit audit = new Audit();
        BeanUtils.copyProperties(auditSaveParam, audit);
        audit.setUpdateTime(new Date());
        auditMapper.update(audit);
        Application application = new Application();
        application.setId(audit.getApplicationId());
        application.setUpdateTime(new Date());
        if(audit.getAuditStatus().equals(AuditStatusEnum.AUDITED.getCode())){
            //审批通过
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            System.out.println("count="+auditQuery);
            Integer count = auditMapper.selectRestAuditCount(auditQuery);
            if(count>0){
                //还有未审核的数据
                auditQuery.setAuditSort(audit.getAuditSort()+1);
                List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
                if(auditVOList !=null && auditVOList.size()>0){
                    AuditVO auditVO = auditVOList.get(0);
                    Audit audit2 = new Audit();
                    audit2.setId(auditVO.getId());
                    audit2.setAuditStatus(AuditStatusEnum.MY_PENDING.getCode());
                    audit2.setUpdateTime(new Date());
                    auditMapper.update(audit2);
                }
                application.setStatus(ApplicationStatusEnum.AUDIT.getCode());
                applicationMapper.update(application);
            }else{
                application.setStatus(ApplicationStatusEnum.AUDITED.getCode());
                applicationMapper.update(application);
            }
        }else{
            //审批驳回
            AuditQuery auditQuery = new AuditQuery();
            auditQuery.setApplicationId(audit.getApplicationId());
            List<AuditVO> auditVOList = auditMapper.selectAudit(auditQuery);
            if(auditVOList != null && auditVOList.size()>0){
                for(int i = 0; i < auditVOList.size(); i++){
                    AuditVO auditVO = auditVOList.get(i);
                    if(auditVO.getAuditStatus().equals(AuditStatusEnum.PENDING.getCode())){
                        auditMapper.deleteById(auditVO.getId());
                    }
                }
            }
            application.setStatus(ApplicationStatusEnum.REJECT.getCode());
            application.setRejectReason(auditSaveParam.getRejectReason());
            applicationMapper.update(application);
        }
    }

    private void assignAuditUserList(AuditVO auditVO) {
        List<String> auditUsernameList = new ArrayList<>();
        List<Long> auditUserIdList = new ArrayList<>();
        List<AuditVO> auditVOList = auditMapper.selectAuditByApplicationId(auditVO.getApplicationId());
        for (int i = 0; i < auditVOList.size(); i++) {
            Long userId = auditVOList.get(i).getAuditUserId();
            auditUserIdList.add(userId);
            UserVO user = userMapper.selectById(userId);
            auditUsernameList.add(user.getUsername());
        }
        StringJoiner stringJoiner = new StringJoiner(",");
        for (String username : auditUsernameList){
            stringJoiner.add(username);
        }
        auditVO.setAuditUserIdList(auditUserIdList);
        auditVO.setAuditUsernameList(stringJoiner.toString());
    }
}
